<template>
  <div class="citylist">
    <div class="citylist-header">
      <van-icon name="arrow-left" @click="()=>{this.$router.push('/Home')}" />
      <h3>城市选择</h3>
      <span></span>
    </div>

    <div class="citylist-main">
      <van-index-bar :sticky="false" :index-list="az">
        <div v-for="(v, i) in citylist" :key="i">
          <van-index-anchor :index="v.title" />
          <van-cell
            v-for="(item, index) in v.children"
            :key="index"
            :title="item.label"
            @click="goHome(item)"
          />
        </div>
      </van-index-bar>
    </div>

    <div class="citylist-footer"></div>
  </div>
</template>

<script>
import { mapMutations } from "vuex";
import axios from "axios";
export default {
  data() {
    return {
      citylist: [],
      az: []
    };
  },
  methods: {
    ...mapMutations(["area"]),
    goHome(label) {
      console.log(label);
      localStorage.setItem('cityid',label.value)
      this.area(label);
      this.$router.go(-1)
    }
  },

  created() {
    //获取数据
    axios.get("/area/city?level=1").then(res => {
      let city1 = res.data.body;
      let city2 = [...city1]; //过滤出来a-z用的
      //转大小写 首字母变成大写
      let A_Z = city2.map(v => {
        //截取首字母，转成大写
        return v.short.slice(0, 1).toUpperCase();
      });
      //去重
      let set = [...new Set(A_Z)];
      //排序
      let a_z = set.sort(); //首字母组成的数组
      //类数组转真数组
      let indexList = [...a_z];
      this.az = indexList;
      //过滤首字母进行排序
      a_z.forEach((v, i) => {
        let arr = city1.filter(item => {
          return item.short.slice(0, 1).toUpperCase() === v;
        });
        a_z[i] = {
          title: v,
          children: [...arr]
        };
      });
      this.citylist = a_z;
      console.log(a_z);
    });
  }
};  
</script>

<style scoped>
.citylist {
  width: 100%;
  height: 100%;
}
.citylist-header {
  width: 100%;
  height: 8%;
  background: #f3f3f3;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 15px;
}
.citylist-header h3 {
  font-size: 18px;
  font-weight: normal;
}
.citylist-header i {
  display: flex;
  align-items: center;
  font-size: 20px;
}
.citylist-main {
  height: 92%;
  overflow: scroll;
}
</style>